package com.greedy.bulls.stock.user.config;

import com.greedy.stock.common.web.vo.ApiRespResult;
import javax.validation.ConstraintViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.validation.ConstraintViolation;
import java.util.List;
import java.util.Set;

/**
 * @Author: Yanxy
 * @Date: Created in:2023-07-30
 * Description: 参数校验异常处理器
 */
@ControllerAdvice
public class ParamValidExceptionHandler {

    /**
     * 捕获所有校验异常信息,  进行封装, 返回给客户端, 捕获的是BindException
     *
     * @param ex 校验异常
     * @return 封装后的异常信息
     */
    @ExceptionHandler(BindException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public ApiRespResult handlerException(BindException ex) {
        // 获取所有校验错误提示
        StringBuffer stringBuffer = new StringBuffer();
        List<FieldError> errors = ex.getBindingResult().getFieldErrors();
        // 遍历属性校验结果集
        for (FieldError fieldError : errors) {
            stringBuffer.append(fieldError.getField()).append(":").append(fieldError.getDefaultMessage());
        }
        // 封装校验异常返回信息
        return ApiRespResult.validError(stringBuffer.toString());
    }


    /**
     * 拦截约束性异常的处理, 比如@NotBlank, 非空的必要性约束等, 捕获的是ConstraintViolationException
     *
     * @param ex 校验异常
     * @return 封装后的异常信息
     */
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ApiRespResult handlerConstraintException(ConstraintViolationException ex) {
        // 获取所有校验错误提示
        StringBuffer stringBuffer = new StringBuffer();
        Set<ConstraintViolation<?>> errors = ex.getConstraintViolations();
        // 遍历属性校验结果集
        for (ConstraintViolation<?> constraintViolation : errors) {
            stringBuffer.append(constraintViolation.getMessage());
        }
        // 封装校验异常返回信息
        return ApiRespResult.validError(stringBuffer.toString());
    }
}
